package com.net.wanjian.networkhospitalmanager.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.bean.LoginReturn;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.consts.SharedPreferencesKeyConst;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.observers.DisposableObserver;

import static com.net.wanjian.networkhospitalmanager.R.mipmap.close;
import static com.net.wanjian.networkhospitalmanager.R.mipmap.password_icon;

/**
 * Description:登录页面
 * Created by lidongcai on 2017/4/22.
 * Email:  lidongcaiocc@163.com
 */
public class LoginActivity extends BaseActivity {
    public static final String HOSPITALID_KEY = "com.wanjian.loginactivity.hospitalid";
    public static final String HOSPITALID_NAME = "com.wanjian.loginactivity.hospitalname";

    @BindView(R.id.login_name_et)
    EditText loginNameEt;
    @BindView(R.id.login_password_et)
    EditText loginPasswordEt;
    @BindView(R.id.login_enter_btn)
    Button loginEnterBtn;
    @BindView(R.id.login_enter_hospital)
    TextView loginEnterHospital;
    @BindView(R.id.login_select_hospital)
    TextView loginSelectHospital;

    private boolean isHint;

    @Override
    protected void initData() {
        String name = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.LOGIN_USER_NAME, "");
        String pw = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.LOGIN_USER_PASSWORD, "");

        loginNameEt.setText(name);
        loginPasswordEt.setText(pw);

        String hospitalId = "";
        String read = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.SELECT_HOSPITAL_KEY, "");

        if (read == "") {
            Bundle bundle = getIntent().getExtras();
            if (null != bundle){
                hospitalId = bundle.getString(HOSPITALID_KEY);
                loginEnterHospital.setText(bundle.getString(HOSPITALID_NAME));
            }
        } else {
            hospitalId = read;
            loginEnterHospital.setText(SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.SELECT_HOSPITAL_NAME, ""));
        }


        if (!"".equals(name) && !"".equals(pw)) {
            JPushInterface.setAliasAndTags(this, "", new LinkedHashSet<String>(), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {

                }
            });

            String deviceId = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.DEVICE_IDENTITY_KEY, "");

            if (!name.isEmpty() && !pw.isEmpty() && !hospitalId.isEmpty()) {
                loginHttpRequest(deviceId, hospitalId, name, pw);
            }
        }


        //选择医院
        loginSelectHospital.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(SelectHospitalActivity.REQUEST_TYPE, "login");
                openActivityForResult(SelectHospitalActivity.class, SelectHospitalActivity.REQUEST_CODE, bundle);
            }
        });

        loginEnterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!NetUtils.isNetworkConnectedShowToast(LoginActivity.this)){
                    return;
                }

                String hospitalId = "";
                String read = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.SELECT_HOSPITAL_KEY, "");

                if (read == "") {
                    Bundle bundle = getIntent().getExtras();
                    if (null != bundle){
                        hospitalId = bundle.getString(HOSPITALID_KEY);
                    }
                } else {
                    hospitalId = read;
                }

                String deviceId = SharedXmlUtil.getInstance().read(SharedPreferencesKeyConst.DEVICE_IDENTITY_KEY, "");
                final String name = loginNameEt.getText().toString().trim();
                final String password = loginPasswordEt.getText().toString().trim();
                if (!name.isEmpty() && !password.isEmpty() && !hospitalId.isEmpty()) {
                    loginHttpRequest(deviceId, hospitalId, name, password);
                }else {
                    ToastUtil.showToast("请输入用户名和密码并选择医院再登录");
                }
            }
        });


        loginPasswordEt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = loginPasswordEt.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (isHint) {
                    if (event.getX() > loginPasswordEt.getWidth()
                            - loginPasswordEt.getPaddingRight()
                            - drawable.getIntrinsicWidth()) {
                        loginPasswordEt.setInputType(0x90);

                        Drawable left = LoginActivity.this.getResources().getDrawable(R.mipmap.password_icon);
                        left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                        Drawable right = LoginActivity.this.getResources().getDrawable(R.mipmap.eye_open);
                        right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());


                        loginPasswordEt.setCompoundDrawables(left, null, right, null);
                    }
                    isHint = false;


                } else {
                    if (event.getX() > loginPasswordEt.getWidth()
                            - loginPasswordEt.getPaddingRight()
                            - drawable.getIntrinsicWidth()) {
                        loginPasswordEt.setInputType(0x81);

                        Drawable left = LoginActivity.this.getResources().getDrawable(password_icon);
                        left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                        Drawable right = LoginActivity.this.getResources().getDrawable(close);
                        right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());

                        loginPasswordEt.setCompoundDrawables(left, null, right, null);
                    }
                    isHint = true;

                }
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SelectHospitalActivity.REQUEST_CODE) {
             if (data != null){
                 loginEnterHospital.setText(data.getStringExtra("hospital").trim());
             }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void loginHttpRequest(String deviceId, String hospitalId, final String name, final String password) {
        ProgressDialogUtils.showProgressDialog(this, null, R.string.login_text);
        HttpUtil.userlogin(deviceId, hospitalId, name, password, new DisposableObserver<LoginReturn>() {
            @Override
            public void onNext(LoginReturn loginReturn) {

                if (Integer.parseInt(loginReturn.getResult()) == ErrorCodeReturn.success) {
                    LoginReturn.DataBean.DefaultUserIdentityBean userIdentity = loginReturn.getData().getDefaultUserIdentity();

                    //保存返回的用户信息
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.TOKEN_KEY, URLDecoderUtil.getDecoder(loginReturn.getData().getToken()));
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.USER_INFO_ID_KEY, URLDecoderUtil.getDecoder(userIdentity.getUserInfoID()));
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.EncryptUser_Identity_ID_key, URLDecoderUtil.getDecoder(userIdentity.getEncryptUserIdentityID()));
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.User_Identity_Tag_key, URLDecoderUtil.getDecoder(userIdentity.getUserIdentityTag()));
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.User_Identity_ID_key, URLDecoderUtil.getDecoder(userIdentity.getUserIdentityID()));

                    //保存登录用户名和密码
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.LOGIN_USER_NAME, name);
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.LOGIN_USER_PASSWORD, password);

                    //保存通知的标签
                    List<String> messageTag = userIdentity.getMessageTag();
                    StringBuilder sb = new StringBuilder();
                    for (String s: messageTag) {
                        sb.append(s+",");
                    }
                    SharedXmlUtil.getInstance().write(SharedPreferencesKeyConst.MESSAGE_TAG_KEY, sb.toString());

                    //设置推送的别名和标签
                    LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(userIdentity.getMessageTag());
                    String replace = userIdentity.getUserIdentityID().replace("-", "_");
                    JPushInterface.setAliasAndTags(LoginActivity.this, replace, linkedHashSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            Log.e(TAG, "gotResult: "+"i="+i+"s="+s+"set="+set);
                        }
                    });

                    openActivity(MainActivity.class);
                    finish();
                }

                if (Integer.parseInt(loginReturn.getResult()) == ErrorCodeReturn.loginError) {
                    ToastUtil.showToast("用户名或密码错误，请重新输入");
                }

                if (Integer.parseInt(loginReturn.getResult()) == ErrorCodeReturn.noAuthority) {
                    ToastUtil.showToast("您没有权限，请使用有权限的账户登录");
                }
            }

            @Override
            public void onError(Throwable e) {
                ProgressDialogUtils.dismissProgressDialog();
            }

            @Override
            public void onComplete() {
                ProgressDialogUtils.dismissProgressDialog();
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

}
